﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using EnvDTE;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;

namespace QuickMAP.UI
{
    public partial class frmTemplate : Form
    {
        public DTE DTEObject = null;

        public frmTemplate()
        {
            InitializeComponent();
        }

        private void frmTemplate_Load(object sender, EventArgs e)
        {
            EnvDTE.TextSelection docSel = DTEObject.ActiveDocument.Selection as TextSelection;
            rchTxtTemplate.Text = docSel.Text;
            combTempType.SelectedIndex = 0;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtFilePath.Text))
            {
                MessageBox.Show("请选择保存路径！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (string.IsNullOrEmpty(rchTxtTemplate.Text.Trim()))
            {
                MessageBox.Show("模板内容不能为空！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (new Regex("\\[0-9]+$").IsMatch(txtFilePath.Text))
            {
                MessageBox.Show("文件名称不能以为纯数字，数字可以用于文件名开开头，用于排序使用！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            File.WriteAllText(txtFilePath.Text, rchTxtTemplate.Text);

            this.Hide();
            frmLoading loading = new frmLoading();
            System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
            {
                loading.ShowDialog();
            }));
            thread.Start();
            Connect.ConnectObj.Reload();
            thread.Abort();
            loading.Close();
            loading.Dispose();
            this.Close();
            this.Dispose(true);
        }

        private void btnFilePath_Click(object sender, EventArgs e)
        {
            saveFileDialog1.InitialDirectory = new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName + "\\Templates";
            saveFileDialog1.ShowDialog();
        }

        private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            txtFilePath.Text = saveFileDialog1.FileName;
        }
    }
}
